import Socket from "@/utils/websocket/index.js"
import glbConfig from '@/common/config.js'
import {
	encrypt,
	decrypt
} from "@/utils/aes.js"
import {
	flagFn
} from '@/api/flag.js'
import store from '@/store'

export let appWebSocket = null
// 获取 token
export const getTokenStorage = () => {
	let token = ''
	try {
		token = uni.getStorageSync('token') || ''
	} catch (e) {
		console.log(e)
	}
	return token
}

// 开启长链接
export function connectSocket() {
	// uni.showLoading({
	// 	title: 'connect',
	// })
	// if (!token) return
	let heartTime = 10
	let heartData = getHeartbeatParam()
	// heartData.flag = 'LOGIN'
	appWebSocket = new Socket({
		url: glbConfig.wsUrl,
		heartData
	}, heartTime, 5, () => {
		console.log('关闭连接中的提示')
		uni.hideLoading()

	});

	uni.$once('websocketRec', () => {
		uni.hideLoading()
		connectSocket()
	})
	appWebSocket.onmessage(onmessage)

	// return new Promise((reslove, reject) => {
	// 	try {

	// 	} catch (e) {
	// 		reslove(true)
	// 		console.log(e)
	// 		//TODO handle the exception
	// 	}
	// })
}

export function sendMessage({
	flag,
	type = 'api',
	content = {}
}) {
	let data = {}
	let token = getTokenStorage();
	let contentData = {
		...content,
		token
	}
	console.log('客户端消息：' + flag, contentData);
	if (glbConfig.isEncryption) {
		data.content = encrypt(JSON.stringify(contentData))
	} else {
		data.content = contentData
	}
	token && (data.token = token)
	type && (data.type = type)
	flag && (data.flag = flag)
	appWebSocket.send(data)
}

// 接收消息
export function onmessage(message) {
	try {
		let type = message.type
		let serverData = {}
		if (glbConfig.isEncryption && !['ping'].includes(type)) {
			serverData = {
				...message,
				back_str: JSON.parse(decrypt(message.back_str))
			}
		} else {
			serverData = message
		}
		if (!['ping'].includes(type)) {
			console.log('服务端消息: ' + serverData.flag, JSON.parse(JSON.stringify(serverData.back_str)));
			['CHECKWITHDRAWAL',
				'checkcharge'
			].includes(serverData.flag) && uni.$emit(serverData.flag, JSON.parse(JSON.stringify(
				serverData
				.back_str)))
		}
		if (type === 'back') {
			consol.log(type, 'token-错误')
		} else if (type === 'api') {
			interceptors(serverData)
		}
	} catch (e) {
		console.log(e)
	}
}

function getHeartbeatParam() {
	let token = getTokenStorage()
	let result = {}
	if (glbConfig.isEncryption) {
		result.content = encrypt(JSON.stringify({
			token
		}))
	} else {
		result.token = token
	}
	result.type = 'ping'
	return result
}



export function getHeartbeatAgain() {
	let data = getHeartbeatParam()
	appWebSocket.getHeartbeat(true, data)
}

function interceptors(data) {
	console.log('data: ', data);
	if (data.back_str.code !== 1 && data.back_str.login_code === '400015') {
		// 在其它地方登录或登录失效，跳转到登录页，并更新下次登录后tabBar下标为0
		uni.showToast({
			title: data.back_str.msg,
			icon: 'none'
		})
		setTimeout(() => {
			store.commit('app/callUserLogout')
			store.commit('app/saveActiveTab', 0)
			uni.setStorageSync('curMenuPagePath', '/pages/tabBar/home/index');
			// #ifdef H5
			if (window.location.pathname == '/pages/auth/auth') {
				return;
			} else {
				// uni.reLaunch({
				// 	url: '/pages/auth/auth?type=0'
				// });
			}
			// #endif 
		}, 1500)
	} else {
		flagFn(data.flag, data.back_str)
	}
}